package com.ihealthway.all.testuitl;

import com.ihealthway.all.groupbuy.vo.UserInfo;
import io.github.elkan1788.mpsdk4j.api.WechatAPI;
import io.github.elkan1788.mpsdk4j.api.WechatAPIImpl;
import io.github.elkan1788.mpsdk4j.vo.MPAccount;
import io.github.elkan1788.mpsdk4j.vo.api.FollowList;
import io.github.elkan1788.mpsdk4j.vo.api.Follower;
import io.github.elkan1788.mpsdk4j.vo.api.Follower2;
import org.nutz.dao.impl.NutDao;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.combo.ComboIocLoader;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.util.ArrayList;
import java.util.List;

/**
 * Sync product MP account users
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
public class SyncProdMpUser {

    private Log logger = Logs.get();

    private NutIoc ioc;

    private MPAccount mpAct;
    private WechatAPI wechatAPI;

    private List<Follower> followers = new ArrayList<>();

    public void init() {
        mpAct = new MPAccount();
        mpAct.setMpId("gh_71469b0885f9");
        mpAct.setAppId("wx3793820ea81974ea");
        mpAct.setAppSecret("c281c93f4bb4ccf01370ae38d09326f2");

        wechatAPI = WechatAPIImpl.create(mpAct);

        try {
            ioc = new NutIoc(new ComboIocLoader("*js", "ioc/"));
        } catch (ClassNotFoundException e) {
            logger.error("Unload the ioc properties file!!!", e);
        }

    }

    public List<String> loadUsers() {
        FollowList fl = wechatAPI.getFollowerList(null);
        return fl.getOpenIds();
    }

    public void insertData(List<Follower> followers){
        List<UserInfo> users = new ArrayList<>();
        followers.forEach( follower -> {
            UserInfo userInfo = new UserInfo();
            userInfo.cloneFromFollower(follower);
            users.add(userInfo);
        });
        try {
            ioc.get(NutDao.class, "dao").insert(users);
        } catch (Exception e) {
            logger.error("Insert user into database fail!!!", e);
        }
    }

    public void syncData() {
        List<String> openIds = loadUsers();
        List<Follower2> openIdList = new ArrayList<>();
        openIds.forEach(openId -> {
            openIdList.add(new Follower2(openId));
            if (openIdList.size() == 99) {
                List<Follower> followers = wechatAPI.getFollowers(openIdList);
                insertData(followers);
                openIdList.clear();
            }
        });

        if (!openIds.isEmpty()) {
            List<Follower> followers = wechatAPI.getFollowers(openIdList);
            insertData(followers);
        }

    }

    public static void main(String[] args) {
        SyncProdMpUser syncProdMpUser = new SyncProdMpUser();
        syncProdMpUser.init();
        syncProdMpUser.syncData();
    }
}
